﻿using AutoMapper;
using MediatR;
using MyMES.Domain.W.Liststructure;
using MyMES.Error;
using MyMES.Infrastructure.Interface;
using MyMES.Read.API.Application.Commends.W.realize;
using MyMES.Read.API.Dtos;

namespace MyMES.Read.API.Application.CommendHandlers.W.realize
{
    public class GetArrivalmanagementCommandHanders : IRequestHandler<GetArrivalmanagementCommands, APIPaging<List<ArrivalmanagementDTO>>>
    {
        private readonly IBaseRepository<ArrivalmanagementDTO> Repository;
        private readonly IMapper mapper;

        public GetArrivalmanagementCommandHanders(IBaseRepository<ArrivalmanagementDTO> Repository, IMapper mapper)
        {
            this.Repository = Repository;
            this.mapper = mapper;
        }

        /// <summary>
        /// 显示到票信息
        /// </summary>
        /// <param name="request">到票管理</param>
        /// <param name="cancellationToken">2025年4月16日10:08:44</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIPaging<List<ArrivalmanagementDTO>>> Handle(GetArrivalmanagementCommands request, CancellationToken cancellationToken)
        {
            APIPaging<List<ArrivalmanagementDTO>> result=new APIPaging<List<ArrivalmanagementDTO>>();
            result.Code = APIEnum.查询成功;
            result.Msg = "查询成功";
            var sql = "select a.Aid,a.ArrivalNumber,a.ArrivalName,a.Arrivaltype,a.ArrivalTime,a.Drawer,a.Invoicenumber,a.Remark,c.Invoiceamount from Arrivalmanagement a inner join ArrivalSales b on a.Aid=b.Aid inner join Salesordersheet c on b.SalesId=c.SalesId where a.IsDelete=false";

            var Arrivalmanagement= Repository.SelectAsync(sql).Result;
            var ArrivalSales = Repository.SelectAsync(sql).Result;
            var Salesordersheet = Repository.SelectAsync(sql).Result;

            var Arrival = mapper.Map<List<ArrivalmanagementDTO>>(Arrivalmanagement);
            var Arrivalsales = mapper.Map<List<ArrivalmanagementDTO>>(ArrivalSales);
            var Sales = mapper.Map<List<ArrivalmanagementDTO>>(Salesordersheet);

            foreach (var item in Arrival)
            {
                item.SalesId = Sales.Where(x => x.SalesId == item.SalesId).FirstOrDefault().SalesId;
            }
            if (!string.IsNullOrEmpty(request.ArrivalNumber))
            {
                Arrival = Arrival.Where(x => x.ArrivalNumber.Contains(request.ArrivalNumber)).ToList();
            }

            result.TotalCount = Arrival.Count;
            result.TotalPage = (int)Math.Ceiling(result.TotalCount * 1.0 / request.PageSize);
            Arrival = Arrival.Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();

            result.data = Arrival;
            return result;
        }
    }
}
